package edu.purdue.cs.aggr.messageprocessor;

import edu.purdue.cs.aggr.AggrException;
import edu.purdue.cs.aggr.Controller;
import edu.purdue.cs.aggr.message.ControllerCommandMessage;
import edu.purdue.cs.aggr.message.Message;
import edu.purdue.cs.aggr.message.VertexUpdateMessage;

public class ControllerCommandMessageProcessor extends MessageProcessor
{

  private Controller controller;
  
  public ControllerCommandMessageProcessor(Controller c) {
    this.controller = c;
  }
  
  @Override
  public void processMessage(Message message) throws AggrException
  {
    ControllerCommandMessage command = (ControllerCommandMessage) message;
    
    System.out.println("Received controller command message: " + command.toString());
    
    if(command.getType().equals("update")) {
      // tell the node to update and reaggregate
      
      String[] nodes = command.getNodeId().split(",");
      
      controller.updatesExpected = nodes.length;
      
      for(String node : nodes) {
        VertexUpdateMessage updateMessage = new VertexUpdateMessage();
        updateMessage.setDestination(node);
        System.out.println("Controller sending update command: " + updateMessage.toString());
        controller.getSender().sendMessage(updateMessage, controller.getLocation(node));
      }
    } else if (command.getType().equals("combine")) {
      String[] nodes = command.getNodeId().split(",");
      controller.combineStarted = System.currentTimeMillis();
      for(String node : nodes) {
        controller.combineNodes(node);
      }
    }
  }
}
